package com.chengke.novel.cacheManager;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chengke.novel.common.constant.CacheConsts;
import com.chengke.novel.dao.BookInfoMapper;
import com.chengke.novel.dao.HomeBookMapper;
import com.chengke.novel.dto.responsParm.HomeBookRespDto;
import com.chengke.novel.entity.BookInfo;
import com.chengke.novel.entity.HomeBook;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 首页推荐小说 缓存管理类
 * @Author CK
 * @Date 2023/3/18
 */

@Component
@RequiredArgsConstructor
public class HomeBookCacheManager {
    private final HomeBookMapper homeBookMapper;

    private final BookInfoMapper bookInfoMapper;

    /**
     * 查询首页小说推荐，并放入缓存中
     */
    @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER,
            value = CacheConsts.HOME_BOOK_CACHE_NAME)
    public List<HomeBookRespDto> listHomeBooks(){
        // 从首页小说推荐表中查询出需要推荐的小说
        LambdaQueryWrapper<HomeBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(HomeBook::getSort);
        List<HomeBook> homeBooks = homeBookMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(homeBooks)){
            // 获取推荐小说ID列表
            List<Long> bookIds = homeBooks.stream().map(HomeBook::getBookId).toList();
            // 根据小说ID列表查询相关的小说信息列表
            List<BookInfo> bookInfos = bookInfoMapper.selectBatchIds(bookIds);
            // 组装 HomeBookRespDto 列表数据并返回
            if (!CollectionUtils.isEmpty(bookInfos)){
                // 将list集合转成map集合，key为id值，value为对象
                Map<Long, BookInfo> bookInfoMap = bookInfos.stream().collect(Collectors.toMap(BookInfo::getId, Function.identity()));
                return homeBooks.stream().map((item) -> {
                    // 获取书籍详细信息
                    BookInfo bookInfo = bookInfoMap.get(item.getBookId());
                    // 创建响应对象
                    HomeBookRespDto bookRespDto = new HomeBookRespDto();
                    bookRespDto.setType(item.getType());
                    bookRespDto.setBookId(item.getBookId());
                    bookRespDto.setPicUrl(bookInfo.getPicUrl());
                    bookRespDto.setBookName(bookInfo.getBookName());
                    bookRespDto.setAuthorName(bookInfo.getAuthorName());
                    bookRespDto.setBookDesc(bookInfo.getBookDesc());
                    return bookRespDto;
                }).toList();
            }
        }


        // 如果为空返回一个空的集合
        return Collections.emptyList();
    }
}
